import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/add_apartment/sectinos/floors.dart";
import "package:ct_pa_majordomo/pages/apartment/add_apartment/widgets/add_building/index.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/widgets/form_select_field.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/header.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:flutter_form_builder/flutter_form_builder.dart";

class AddApartment extends StatefulWidget {
  const AddApartment({super.key});

  @override
  State<AddApartment> createState() => _AddApartmentState();
}

class _AddApartmentState extends State<AddApartment> {
  final GlobalKey<FormBuilderState> _formKey = GlobalKey<FormBuilderState>();
  final List<int> _numList = List.generate(99, (index) => index + 1);
  final Text _required =
      const Text("*", style: TextStyle(color: ThemeVars.colorError));
  List _groups = [];
  List<Map> _floorData = [];

  FormBuilderState get _formState => _formKey.currentState!;

  Map<String, FormBuilderFieldState> get _fields => _formState.fields;

  Map<String, dynamic> get _instantValue => _formState.instantValue;

  Future<void> _getGroups() async {
    try {
      EasyLoading.show();
      List resData = await apartmentApi.getGroups();
      EasyLoading.dismiss();
      setState(() => _groups = resData);
    } catch (error) {
      print(error);
    }
  }

  Future<void> _changeGroup() async {
    Map? popped = await showRoundedBottomSheet(
      builder: (context) => BottomSheetSelect(
        items: _groups,
        compare: (item) => item["groupId"] == _fields["groupId"]?.value,
        itemAsString: (item) => item["groupName"],
      ),
    );
    if (popped != null) _fields["groupId"]?.didChange(popped["groupId"]);
  }

  Future<void> _changeNum(String field) async {
    int? popped;
    if (field != "roomPrefix") {
      int? value = _fields[field]?.value;
      popped = await showRoundedBottomSheet(
        builder: (context) => BottomSheetSelect(
          items: _numList,
          compare: (item) => item == value,
        ),
      );
    }


    if (popped != null) {
      _fields[field]?.didChange(popped);
    }
    int floors = _instantValue["floors"];
    int rooms = _instantValue["rooms"];
    // String roomPrefix = _fields[field]?.value;
    setState(() {
      _floorData = List.generate(floors, (floor) {
        List<String> roomNameList = [];
        for (int i = 1; i <= rooms; i++) {
          roomNameList.add("${_instantValue["roomPrefix"]}${floor + 1}${i < 10 ? "0$i" : i}");
        }
        return {"floor": floor + 1, "room": rooms, "roomNameList": roomNameList};
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _getGroups();
  }

  @override
  Widget build(BuildContext context) {
    print(_floorData);
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: const Header(title: Text("添加整栋")),
      body: Stack(
        children: [
          FormBuilder(
            key: _formKey,
            child: Column(
              // crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                MenuBlock(
                  borderRadius: BorderRadius.zero,
                  items: [
                    MenuBlockItem(
                      text: "分组",
                      onTap: _changeGroup,
                      prefix: _required,
                      suffix: FormSelectField(
                        name: "groupId",
                        itemAsString: (item) {
                          Map? found = _groups.firstWhere(
                                (ele) => ele["groupId"] == item,
                            orElse: () => null,
                          );
                          return found?["groupName"] ?? "";
                        },
                      ),
                    ),
                    MenuBlockItem(
                      prefix: _required,
                      text: "整栋名称",
                      suffix: FormBuilderTextField(
                        decoration: const InputDecoration(hintText: "请输入"),
                        textAlign: TextAlign.right,
                        name: "buildingName",
                      ),
                    ),
                    MenuBlockItem(
                      prefix: _required,
                      text: "总层数",
                      onTap: () => _changeNum("floors"),
                      suffix: const FormSelectField(name: "floors"),
                    ),
                    MenuBlockItem(
                      prefix: _required,
                      text: "每层房间数",
                      onTap: () => _changeNum("rooms"),
                      suffix: const FormSelectField(initialValue: 1, name: "rooms"),
                    ),
                    MenuBlockItem(
                      text: "房间号加前缀",
                      suffix: FormBuilderTextField(
                        decoration: const InputDecoration(
                          counterText: "",
                          hintText: "请输入1位数字/字母",
                        ),
                        inputFormatters: [
                          FilteringTextInputFormatter.allow(RegExp(r"[a-zA-Z1-9]")),
                        ],
                        maxLength: 1,
                        textAlign: TextAlign.right,
                        name: "roomPrefix",
                        onChanged: (value) => _changeNum("roomPrefix"),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 15),
                Expanded(child: Floors(
                  floors: _floorData,
                  onChanged: (value) => setState(() => _floorData = value),
                ),)

              ],
            ),
          ),
          Positioned(
              bottom: 0,
              left: 0,
              width: MediaQuery.of(context).size.width,
              child: Container(
                padding: const EdgeInsets.all(ThemeVars.paddingPage),
                decoration: const BoxDecoration(
                  color: ThemeVars.colorBackground,
                ),
                child: Button(
                    type: ButtonType.primary,
                    onPressed: () {
                      print(_floorData);
                      print(_instantValue);
                      Navigator.push(
                        context,
                        CupertinoPageRoute(builder: (BuildContext context) {
                          return AddBuilding(
                            groupId: _instantValue["groupId"],
                            buildingName: _instantValue["buildingName"],
                            floors: _floorData,
                          );
                        })
                      );
                    },
                    child: const Text("下一步")
                ),
              )
          ),
        ],
      )
    );
  }
}
